package repository

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEnv"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/FileName"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/OS/ShellUtils"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/String"
	"go-fox-edge-kernel-manager/utils/ProcessUtils"
	"strconv"
)

type repoLocalAppStartService struct {
}

func (e *repoLocalAppStartService) RestartProcess(appName, appType string) error {
	// 简单校验参数
	if Method.HasEmpty(appName, appType) {
		return errors.New("参数不能为空:appName, appType")
	}

	appPort, err := LocalAppPort.GetServicePort(appName, appType)
	if err != nil {
		return err
	}

	// 重启设备服务进程
	shellName := FileName.GetOsFilePath(commEnv.Service.WorkDir + "/shell/restart.sh " + appType + "/" + appName + " -p" + strconv.Itoa(appPort))
	resultList, err := ShellUtils.ExecuteShell(shellName)
	if err != nil {
		return err
	}
	if len(resultList) <= 1 {
		return errors.New(resultList[0])
	}

	return nil
}

func (e *repoLocalAppStartService) StopProcess(appName, appType string) error {
	// 简单校验参数
	if Method.HasEmpty(appName, appType) {
		return errors.New("参数不能为空:appName, appType")
	}

	shellFileInfoList := LocalAppConf.GetConfFileInfoList()
	ProcessUtils.ExtendAppStatus(shellFileInfoList)

	for _, data := range shellFileInfoList {
		if appName != data["appName"] {
			continue
		}
		if appType != data["appType"] {
			continue
		}
		if appType == "kernel" {
			continue
		}

		// 获得进程的PID，如果为空，则说明该进程并没有启动
		pid := data["pid"]
		if pid != nil {
			// kill掉该进程
			ShellUtils.ExecuteShell("kill -9 " + String.ToString(pid))
		}
	}

	return nil
}
